import sys
import string

# 字符串中插入变量，想创建一个内嵌变量的字符串，变量被它的值所表示的字符串替换掉
def demo_1():
    s = '{name} has {n} messages.'
    result = s.format(name='kepler', n=37)
    print(result)

# 使用vars函数进行替换，vars函数返回变量的键值对map
def demo_2():
    name = 'kepler'
    n = 37
    s = '{name} has {n} messages.'
    result = s.format_map(vars())
    print(result)

class Info:
    def __init__(self, name, n):
        self.name = name
        self.n = n

# vars函数也适用于对象实例
def demo_3():
    a = Info('kepler', '4')
    s = '{name} has {n} messages.'
    result = s.format_map(vars(a))
    print(result)

class safesub(dict):
    def __missing__(self, key):
        return '{' + key + '}'

# format和format_map的缺陷就是不能很好的处理变量缺失的情况
# __missing__()方法可以处理缺失值情况
def demo_4():
    s = '{name} has {n} messages.'
    name = 'kepler'
    result = s.format_map(safesub(vars()))
    print(result)

# 可以将变量替换步骤用一个工具函数封装起来
# sys._getframe(1)返回调用者的栈帧，可以从中访问属性f_locals来获得局部变量
def sub(text):
    return text.format_map(safesub(sys._getframe(1).f_locals))

def demo_5():
    name = 'kepler'
    n = 10
    print(sub('hello {name}'))
    print(sub('you have {n} messages.'))
    print(sub('you favorite color is {color}'))

# 使用字符串模板
def demo_6():
    name = 'kepler'
    n = 10
    s = string.Template('$name has $n messages.')
    result = s.substitute(vars())
    print(result)

if __name__ == '__main__':
    # demo_1()
    # demo_2()
    # demo_3()
    # demo_4()
    # demo_5()
    demo_6()